/*	Brian Kirkpatrick
 *	String Tree class
 *	Begun 6/23/2010
 */

#include "stringTree.h"

stringTree::stringTree() {
	type = TT_ELEMENT;
	value = "";
	child = NULL;
	next = NULL;
}

stringTree::stringTree(string v) {
	type = TT_ELEMENT;
	value = v;
	child = NULL;
	next = NULL;
}

stringTree::stringTree(string v, TreeType t) {
	type = t;
	value = v;
	child = NULL;
	next = NULL;
}

stringTree::~stringTree() {
	if (child != NULL) {
		delete child;
		child = NULL;
	}
	if (next != NULL) {
		delete next;
		next = NULL;
	}
}

string stringTree::getValue() {
	return value;
}

void stringTree::setValue(string v) {
	value = v;
}

TreeType stringTree::getType() {
	return type;
}

void stringTree::setType(TreeType t) {
	type = t;
}

void stringTree::print() {
	stringTree * a = NULL;
	stringTree * v = NULL;
	switch (type) {
		case TT_COMMENT:
			printf("<!-- %s -->", value.c_str());
			break;
		case TT_DECLARATION:
			printf("<?xml");
			a = child;
			while (a != NULL) {
				if (a->type == TT_ATTRIBUTE) {
					printf(" %s", a->value.c_str());
					v = a->child;
					while (v != NULL) {
						if (v->type == TT_VALUE) {
							printf("=\"%s\"", v->value.c_str());
						}
						v = v->next;
					}
				}
				a = a->next;
			}
			printf("?>");
			break;
		case TT_ATTRIBUTE:
		case TT_VALUE:
			break;
		case TT_TEXT:
			printf("%s", value.c_str());
			break;
		case TT_ELEMENT:
		default:
			// Output as element: <{value} {attribiute=value}.other
			printf("<%s", value.c_str());
			a = child;
			while (a != NULL) {
				if (a->type == TT_ATTRIBUTE) {
					printf(" %s", a->value.c_str());
					v = a->child;
					while (v != NULL) {
						if (v->type == TT_VALUE) {
							printf("=\"%s\"", v->value.c_str());
						}
						v = v->next;
					}
				}
				a = a->next;
			}
			if (child != NULL) {
				printf(">");
			}
			stringTree * children = child;
			while (children != NULL) {
				if (children->type != TT_ATTRIBUTE && children->type != TT_VALUE) {
					children->print();
				}
				children = children->next;
			}
			if (child == NULL) {
				printf("/>");
			} else {
				printf("</%s>", value.c_str());
			}
			break;
	}
}

void stringTree::addChild(stringTree * c) {
	if (child == NULL) {
		child = c;
		return;
	}
	stringTree * children = child;
	while (children->next != NULL) {
		children = children->next;
	}
	children->next = c;
}

void stringTree::addSibling(stringTree * s) {
	if (next == NULL) {
		next = s;
		return;
	}
	stringTree * siblings = next;
	while (siblings->next != NULL) {
		siblings = siblings->next;
	}
	siblings->next = s;
}

int stringTree::numChildren() {
	int counter = 0;
	stringTree * children = child;
	while (children != NULL) {
		children = children->next;
		counter++;
	}
	return counter;
}

stringTree * stringTree::getChild() {
	return child;
}

stringTree * stringTree::getNext() {
	return next;
}
